from loguru import logger
import socket
import threading
import os
import struct
import time


def sending_file(connection, address):
    try:
        file_info_size = struct.calcsize('128sl')

        buf = connection.recv(file_info_size)

        if buf:
            file_name, file_size = struct.unpack('128sl', buf)
            file_name = file_name.decode().strip('\00')
            _time = time.strftime("%Y-%m-%d-%H：%M", time.localtime())
            file_new_dir = os.path.join('D:\\RPALogFiles\\', address, _time)
            if not os.path.exists(file_new_dir):
                os.makedirs(file_new_dir)

            file_new_name = os.path.join(file_new_dir, file_name)

            received_size = 0

            w_file = open(file_new_name, 'wb')

            logger.debug("Start Receiving File: %s" % file_name)

            while not received_size == file_size:
                r_data = connection.recv(10240)
                received_size += len(r_data)
                w_file.write(r_data)

            w_file.close()

            logger.debug("接收完成！")

        connection.close()

    except Exception as e:
        logger.error(e)


if __name__ == '__main__':
    logger.add('server.log')
    host = socket.gethostname()
    logger.debug('local is (192.168.0.124, 9999)')

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, 9999))
    sock.listen(30)

    logger.debug("---------------服务已启动---------------")

    while True:
        connection, address = sock.accept()
        logger.debug("接收地址：%s" % str(address))
        thread = threading.Thread(target=sending_file, args=(connection, address[0]))
        thread.start()
